package com.jhhc.Config;


import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;


/**
 * @Author ZhangLe 注意这个扫描的包 你的不同mapper那个数据库使用写在对应的包下 对POJO service无关
 * @Date 2020/11/20 19:46
 */
@Configuration
@MapperScan(value = {"com.jhhc.RHDB.Data.Dao","com.jhhc.RHDB.RiverForecast.Calculate.dao"}, sqlSessionFactoryRef = "sqlSessionFactory1")
@Transactional(rollbackFor = Exception.class)
public class RHDBConfig {

    public static class MybatisPreprocessConfig {
        /**
         * 和总配置文件注入bean名称一致 其他无需修改
         */
        @Autowired
        @Qualifier("rhdbDataSource")
        private DataSource ds1;
        @Bean(name = "sqlSessionFactory1")
        @Primary
        public SqlSessionFactory sqlSessionFactory1() throws Exception {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(ds1);
            return sqlSessionFactoryBean.getObject();
        }

        @Bean("sqlSessionFactory1")
        public SqlSessionFactory db1SqlSessionFactory(@Qualifier("rhdbDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            // mapper的xml形式文件位置必须要配置，不然将报错：no statement （这种错误也可能是mapper的xml中，namespace与项目的路径不一致导致）
            //bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/db1/*.xml"));
            return bean.getObject();
        }

        @Bean("db1SqlSessionTemplate")
        public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory){
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }
}


